package com.chang.bootplus.base.utils;


import com.chang.bootplus.base.exception.BusException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;

/**
 * @author : xukun
 * @date : 2020/10/26
 */
public class FileUtils {

    private static Logger logger = LoggerFactory.getLogger(FileUtils.class);

    /**
     * 清理指定目录下的空文件夹
     *
     * @param dir
     */
    public static void clearNullDir(File dir) {
        File[] dirs = dir.listFiles();
        for (int i = 0; i < dirs.length; i++) {
            if (dirs[i].isDirectory()) {
                clearNullDir(dirs[i]);
            }
        }
        if (dir.isDirectory()) {
            dir.delete();
        }
    }

    /**
     * 根据路径清理本地图片资源
     *
     * @param localUrl
     * @return int数组[existCount, deleteCount]
     */
    public static int[] deleteLocalImage(String localUrl) {
        File file = new File(localUrl);
        int deleteCount = 0;
        int existCount = 0;
        if (file.exists()) {
            existCount++;
            boolean deleteFlag = file.delete();
            if (deleteFlag) {
                deleteCount++;
            }
        }
        return new int[]{existCount, deleteCount};
    }

    /**
     * inputStream 转 File
     */
    public static File inputStreamToFile(InputStream ins, String name, String tempDir) throws IOException {
        //System.getProperty("java.io.tmpdir")临时目录+File.separator目录中间的间隔符+文件名
//        String tempDir = System.getProperty("user.dir") + "\\upimages\\temp\\";
        File dir = new File(tempDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        File file = new File(tempDir + name);
        OutputStream os = new FileOutputStream(file);
        int bytesRead;
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((bytesRead = ins.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        ins.close();
        return file;
    }

    /**
     * file转multipartFile
     */
    public static MultipartFile fileToMultipartFile(File file) throws IOException {
        FileItem item = new DiskFileItem("formFieldName",
                Files.probeContentType(file.toPath()),
                false,
                file.getName(),
                (int) file.length(),
                file.getParentFile());
        int bytesRead;
        byte[] buffer = new byte[8192];
        FileInputStream fis = new FileInputStream(file);
        OutputStream os = item.getOutputStream();
        while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
        os.close();
        fis.close();
        return new CommonsMultipartFile(item);
    }

    /**
     * 网络图片url转MultipartFile
     */
    public static MultipartFile urlToMultipartFile(String url, String tempPath) {
        File file;
        MultipartFile multipartFile;
        try {
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(url).openConnection();
            httpUrl.connect();
            String[] urls = url.split("\\?");//有的网络图片可能带有参数
            String fileSuffixName = urls[0].substring(urls[0].lastIndexOf("."));
            file = FileUtils.inputStreamToFile(httpUrl.getInputStream(), System.currentTimeMillis() + fileSuffixName, tempPath);
            logger.info("---------" + file + "-------------");

            multipartFile = FileUtils.fileToMultipartFile(file);
            httpUrl.disconnect();
        } catch (IOException e) {
            throw new BusException("网络错误");
        }
        return multipartFile;
    }

    public static void main(String[] args) {
        String tempDir = System.getProperty("user.dir") + "\\upimages\\temp\\";
        MultipartFile multipartFile = urlToMultipartFile("http://192.168.1.82:8089/slkj/upimages/2020/11/bfcbdfb3-c4b4-4994-9933-2bb012b2d995.png", tempDir);
        System.out.println(multipartFile.getOriginalFilename());
        System.out.println(multipartFile.getContentType());
        System.out.println(multipartFile.getSize());
        System.out.println(multipartFile.getName());
    }
}

